package com.lg.order.producer.rabbit;

import com.lg.order.producer.config.MyMQConfig;
import com.lg.order.producer.entity.MessageEntity;
import com.lg.order.producer.service.MessageService;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author by Mr. Li 2020/12/11 11:02
 */
@Slf4j
@Component
@RabbitListener(queues = {MyMQConfig.DISTRIBUTED_TRANSACTION_QUEUE})
public class MyRabbitListener {
    @Autowired
    private MessageService mqMessageService;

    @RabbitHandler
    public void listener(Message message, MessageEntity sendMessage,
                         Channel channel) {

        try {
            channel.basicQos(1); // 一次处理一个请求
            final Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, StandardCharsets.UTF_8);
                    log.info("[x] Received ' {} '", message);
                    try {
                        log.info("consumer is success!!!");

                    } finally {

                    }
                }
            };

            byte[] body = message.getBody();

            System.out.println("接受到消息..." + sendMessage);
            // 调用 业务逻辑，进行业务处理
            sendMessage.setMessageStatus(1);
            sendMessage.setUpdateTime(new Date());
            Boolean isSuccess = mqMessageService.saveOrUpdate(sendMessage);
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.getHeaders();
            if (isSuccess) {
                // 手动签收消息，通知MQ删除此消息
                channel.basicAck(messageProperties.getDeliveryTag(), false);
                log.info("scoreConsumer handler success.");
            }
            log.info("[信息接受成功！]");
            //channel.basicConsume(MyMQConfig.DISTRIBUTED_TRANSACTION_QUEUE, false, consumer);
        } catch (IOException e) {
            log.error("信息消费失败");
        }
    }
}
